<template>
  <blog-item
    :blog="blog"
    :key="blog.id"
    v-for="blog in blogs"
  />
  <div class="loading-more">{{loadingText}}</div>
</template>

<script>
import { ref, reactive, onMounted } from "vue";

import BlogItem from "../../../components/blog-item/BlogItem";

import { getBlogs } from "../../../network/blog";
import debounce from "../../../utils/debounce";

export default {
  name: "BlogShow",
  components: { BlogItem },
  setup() {
    const blogs = ref([]); //储存微博数据
    const loadingText = ref("加载更多……"); // 加载文本
    const currentPage = ref(1); //页码
    const windowHeight = ref(
      document.documentElement.clientHeight || document.body.clientHeight
    ); //视口高度

    //获取微博
    const gainBlogs = async (page) => {
      const result = await getBlogs({ page, limit: 10 });
      // console.log(result);
      if (result.status !== 200) {
        return console.log(result.message);
      }
      currentPage.value = result.data.page + 1;
      blogs.value =
        page === 1
          ? result.data.result
          : [...blogs.value, ...result.data.result];
      loadingText.value =
        (result.data.result.length < 10 ? "已加载全部~" : "加载更多……");
    };

    //滚动到底部加载更多事件
    const listenToScroll = () => {
      //变量scrollTop是滚动条滚动时，距离顶部的距离
      var scrollTop =
        document.documentElement.scrollTop || document.body.scrollTop;
      //变量scrollHeight是滚动条的总高度
      var scrollHeight =
        document.documentElement.scrollHeight || document.body.scrollHeight;

      if (scrollTop + windowHeight.value > scrollHeight - 100) {
        loadingText.value === "加载更多……" && gainBlogs(currentPage.value);
      }
    };

    //监听滚动事件
    window.addEventListener("scroll", debounce(listenToScroll, 200));
    onMounted(() => {
      gainBlogs(currentPage.value);
    });

    return {
      blogs,
      gainBlogs,
      loadingText,
    };
  },
};
</script>

<style scoped lang='stylus' >
.loading-more
  margin 10px 0
  text-align center
</style>